interface HistoryItem {
  code: string;
  type: string;
  date: string;
  selected?: boolean;
}

interface HistoryPageData {
  historyList: HistoryItem[];
  originalList: HistoryItem[];
  currentType: string; // 'all' | 'inbound' | 'outbound'
  selectedCount: number;
  isSelectMode: boolean;
  startDate: string;
  endDate: string;
  showDateFilter: boolean;
  lastExportDate: string;
}

interface HistoryPageMethods {
  loadHistory: () => void;
  switchType: (e: WechatMiniprogram.TouchEvent) => void;
  filterHistory: () => void;
  toggleSelectMode: () => void;
  toggleSelect: (e: WechatMiniprogram.TouchEvent) => void;
  exportAll: () => void;
  exportSelected: () => void;
  exportRecords: (records: HistoryItem[]) => void;
  clearHistory: () => void;
  toggleDateFilter: () => void;
  setStartDate: (e: WechatMiniprogram.TouchEvent) => void;
  setEndDate: (e: WechatMiniprogram.TouchEvent) => void;
  applyDateFilter: () => void;
  checkExportReminder: () => void;
}

Page<HistoryPageData, HistoryPageMethods>({
  data: {
    historyList: [],
    originalList: [],
    currentType: 'all',
    selectedCount: 0,
    isSelectMode: false,
    startDate: '',
    endDate: '',
    showDateFilter: false,
    lastExportDate: ''
  },

  onLoad() {
    this.loadHistory();
    this.checkExportReminder();
  },

  onShow() {
    this.loadHistory();
  },

  // 检查是否需要导出提醒
  checkExportReminder() {
    const lastExportDate = wx.getStorageSync('lastExportDate') || '';
    const today = new Date().toISOString().split('T')[0];
    
    if (lastExportDate && lastExportDate !== today) {
      const lastExport = new Date(lastExportDate);
      const daysSinceLastExport = Math.floor((new Date().getTime() - lastExport.getTime()) / (1000 * 60 * 60 * 24));
      
      if (daysSinceLastExport >= 7) { // 7天未导出提醒
        wx.showModal({
          title: '数据导出提醒',
          content: '您已经7天未导出数据，建议及时导出备份',
          confirmText: '立即导出',
          cancelText: '稍后提醒',
          success: (res) => {
            if (res.confirm) {
              this.exportAll();
            }
          }
        });
      }
    }
  },

  // 切换日期筛选显示
  toggleDateFilter() {
    this.setData({
      showDateFilter: !this.data.showDateFilter
    });
  },

  // 设置开始日期
  setStartDate(e: WechatMiniprogram.TouchEvent) {
    this.setData({
      startDate: e.detail.value
    });
  },

  // 设置结束日期
  setEndDate(e: WechatMiniprogram.TouchEvent) {
    this.setData({
      endDate: e.detail.value
    });
  },

  // 应用日期筛选
  applyDateFilter() {
    const { startDate, endDate, originalList, currentType } = this.data;
    let filteredList = [...originalList];

    // 按日期筛选
    if (startDate && endDate) {
      filteredList = filteredList.filter(item => {
        const itemDate = item.date.split(' ')[0];
        return itemDate >= startDate && itemDate <= endDate;
      });
    }

    // 按类型筛选
    if (currentType !== 'all') {
      filteredList = filteredList.filter(item => item.type === currentType);
    }

    this.setData({
      historyList: filteredList,
      showDateFilter: false
    });
  },

  // 加载历史记录
  loadHistory() {
    const historyList = wx.getStorageSync('scanHistory') || [];
    historyList.forEach((item: HistoryItem) => {
      item.selected = false;
    });
    this.setData({ 
      historyList,
      originalList: [...historyList],
      selectedCount: 0,
      isSelectMode: false
    });
    this.filterHistory();
  },

  // 切换记录类型
  switchType(e: WechatMiniprogram.TouchEvent) {
    const type = e.currentTarget.dataset.type;
    this.setData({ 
      currentType: type,
      isSelectMode: false,
      selectedCount: 0
    });
    this.filterHistory();
  },

  // 过滤历史记录
  filterHistory() {
    const { originalList, currentType } = this.data;
    if (currentType === 'all') {
      this.setData({ 
        historyList: [...originalList]
      });
    } else {
      const filteredList = originalList.filter(item => item.type === currentType);
      this.setData({ 
        historyList: filteredList
      });
    }
  },

  // 切换选择模式
  toggleSelectMode() {
    const { isSelectMode } = this.data;
    this.setData({ 
      isSelectMode: !isSelectMode,
      selectedCount: 0
    });
    // 重置所有选择状态
    const historyList = this.data.historyList.map(item => ({
      ...item,
      selected: false
    }));
    this.setData({ historyList });
  },

  // 选择/取消选择单个记录
  toggleSelect(e: WechatMiniprogram.TouchEvent) {
    if (!this.data.isSelectMode) return;
    
    const index = e.currentTarget.dataset.index;
    const historyList = this.data.historyList;
    historyList[index].selected = !historyList[index].selected;
    
    const selectedCount = historyList.filter(item => item.selected).length;
    this.setData({ 
      historyList,
      selectedCount
    });
  },

  // 导出所有记录
  exportAll() {
    if (this.data.historyList.length === 0) {
      wx.showToast({
        title: '暂无记录可导出',
        icon: 'none'
      });
      return;
    }
    this.exportRecords(this.data.historyList);
  },

  // 导出选中的记录
  exportSelected() {
    const selectedRecords = this.data.historyList.filter(item => item.selected);
    if (selectedRecords.length === 0) {
      wx.showToast({
        title: '请选择要导出的记录',
        icon: 'none'
      });
      return;
    }
    this.exportRecords(selectedRecords);
  },

  // 导出记录的具体实现
  exportRecords(records: HistoryItem[]) {
    try {
      // 使用原始数据列表确保数据一致性
      const allRecords = this.data.originalList;
      const recordsToExport = this.data.isSelectMode ? records : allRecords;

      // 生成CSV内容，添加BOM头确保Excel正确识别中文
      let csvContent = '\ufeff';
      
      // 根据当前选择的类型和记录类型生成不同的表头
      const currentType = this.data.currentType;
      const isInbound = currentType === 'inbound';
      const isAll = currentType === 'all';

      // 根据类型过滤数据
      const filteredRecords = isAll ? recordsToExport : 
        recordsToExport.filter(item => item.type === currentType);

      if (isAll) {
        // 全部记录使用简单格式
        csvContent += '日期\t\t\t\t\t\t\t\t\t\t,设备号\t\t\t\t\t\t\t\t\t\t,操作类型\t\t\t\t\t\t\t\n';
        filteredRecords.forEach(item => {
          const type = item.type === 'inbound' ? '入库' : '出库';
          csvContent += `"${item.date}"\t\t\t\t\t\t\t\t\t\t,"${item.code}"\t\t\t\t\t\t\t\t\t\t,"${type}"\t\t\t\t\t\t\t\n`;
        });
      } else if (isInbound) {
        // 入库文档表头
        csvContent += '日期\t\t\t\t\t\t\t\t\t\t,设备号\t\t\t\t\t\t\t\t\t\t,来源\t\t\t\t\t\t\t\t\t\t,数量\t\t\t\t\t\t\t\t\t\t,入库人\t\t\t\t\t\t\t\t\t\t,备注\t\t\t\t\t\t\t\t\t\t\n';
        
        // 添加数据行
        filteredRecords.forEach(item => {
          csvContent += `"${item.date}"\t\t\t\t\t\t\t\t\t\t,"${item.code}"\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t\n`;
        });
      } else {
        // 出库文档表头
        csvContent += '日期\t\t\t\t\t\t\t\t\t\t,设备编号\t\t\t\t\t\t\t\t\t\t,使用人\t\t\t\t\t\t\t\t\t\t,管理师账号\t\t\t\t\t\t\t\t\t\t,数量\t\t\t\t\t\t\t\t\t\t,单位\t\t\t\t\t\t\t\t\t\t,出库人\t\t\t\t\t\t\t\t\t\t,出库类别\t\t\t\t\t\t\t\t\t\t,备注\t\t\t\t\t\t\t\t\t\t\n';
        
        // 添加数据行
        filteredRecords.forEach(item => {
          csvContent += `"${item.date}"\t\t\t\t\t\t\t\t\t\t,"${item.code}"\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t,""\t\t\t\t\t\t\t\t\t\t\n`;
        });
      }

      const fsm = wx.getFileSystemManager();
      // 根据类型设置不同的文件名
      let fileName;
      if (isAll) {
        fileName = `出入库记录_${new Date().getTime()}.csv`;
      } else {
        fileName = `${isInbound ? '入库' : '出库'}记录_${new Date().getTime()}.csv`;
      }
      const tempPath = `${wx.env.USER_DATA_PATH}/${fileName}`;

      try {
        // 写入文件
        fsm.writeFileSync(tempPath, csvContent, 'utf8');
        
        // 更新最后导出日期
        const today = new Date().toISOString().split('T')[0];
        wx.setStorageSync('lastExportDate', today);
        this.setData({ lastExportDate: today });

        // 显示成功提示并引导用户
        wx.showModal({
          title: '导出成功',
          content: '文件已保存到手机存储，请在手机文件管理器中查看',
          confirmText: '我知道了',
          showCancel: false,
          success: () => {
            console.log('文件保存位置：', tempPath);
          }
        });

      } catch (error) {
        console.error('写入文件失败：', error);
        wx.showToast({
          title: '导出失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('导出失败：', error);
      wx.showToast({
        title: '导出失败',
        icon: 'error'
      });
    }
  },

  // 清空历史记录
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空历史记录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('scanHistory');
          this.setData({ 
            historyList: [],
            originalList: [],
            selectedCount: 0,
            isSelectMode: false
          });
          wx.showToast({
            title: '已清空',
            icon: 'success'
          });
        }
      }
    });
  }
}); 